package com.hubujun.driverlicense.core;

import junit.framework.Assert;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;

import com.hubujun.driverlicense.util.Ln;

public class LZHandlerThread {

	public static long mainThreadID = -1L;

	private HandlerThread handlerThread;

	private Handler handler;

	public LZHandlerThread() {
		handlerThread = null;
		handler = null;
		init();
	}

	public static void postToUIThread(Runnable runnable) {
		if (runnable != null)
			new Handler(Looper.getMainLooper()).post(runnable);
	}

	static void postToUIThreadFront(Runnable runnable) {
		if (runnable != null)
			new Handler(Looper.getMainLooper()).postAtFrontOfQueue(runnable);
	}

	private void init() {
		Ln.d("LZHandlerThread init");
		handler = null;
		handlerThread = new HandlerThread("LZHandlerThread", 1);
		handlerThread.start();
	}

	public static boolean isMainThread() {
		Assert.assertFalse("mainThreadID not init ", mainThreadID == -1L);
		boolean result = true;
		if (Thread.currentThread().getId() != mainThreadID)
			result = false;
		return result;
	}

	public static void setMainThreadId(long id) {
		if (mainThreadID < 0L && id > 0L)
			mainThreadID = id;
	}

	public int postToHandlerThreadFront(final BackgroundTask task) {
		byte result;
		if (task == null)
			result = -1;
		else if (new Handler(handlerThread.getLooper()).postAtFrontOfQueue(new Runnable() {

			@Override
			public void run() {
				task.doInBackground();
				postToUIThreadFront(new Runnable() {
					@Override
					public void run() {
						task.onPostExecute();
					}
				});
			}
		}))
			result = 0;
		else
			result = -2;
		return result;
	}

	public int post(Runnable runnable) {
		byte result;
		if (runnable == null) {
			result = -1;
		} else {
			if (handler == null)
				handler = new Handler(handlerThread.getLooper());
			handler.post(runnable);
			result = 0;
		}
		return result;
	}

	public Looper getLooper() {
		return handlerThread.getLooper();
	}

	public int syncReset() {
		Assert.assertTrue("syncReset should in mainThread", isMainThread());
		final byte[] lock = new byte[0];
		BackgroundTask task = new BackgroundTask() {

			@Override
			public boolean doInBackground() {
				Ln.d("syncReset doInBackground");
				handlerThread.quit();
				init();
				synchronized (lock) {
					lock.notify();
				}

				return true;
			}

			@Override
			public boolean onPostExecute() {
				Ln.d("syncReset onPostExecute");
				return true;
			}

		};
		int result;
		synchronized (lock) {
			result = postToHandlerThreadFront(task);
			if (result == 0) {
				try {
					lock.wait();
				} catch (Exception exception1) {
				}
			}
		}

		return result;
	}
}
